package com.rtx.wms.std.log.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.qimen.api.QimenRequest;
import com.rtx.api.utils.MultipleDataSource;
import com.rtx.edi.model.log.po.PlApiRequestContentLog;
import com.rtx.edi.model.log.po.PlApiRequestLog;
import com.rtx.wms.std.log.bean.WmsLogBo;
import com.rtx.wms.std.log.mapper.WmsLogContentLogMapper;
import com.rtx.wms.std.log.mapper.WmsLogMapper;
import com.taobao.api.internal.util.XmlWriter;

import cn.hutool.core.lang.UUID;

public abstract class AbsWmsLogService {

	@Autowired
	WmsLogMapper wmsLogMapper;
	
	@Autowired
	WmsLogContentLogMapper wmsLogContentLogMapper;
	
	
	Logger log = LoggerFactory.getLogger(this.getClass());
	
	
	public void recordLog(String oriDatasource,WmsLogBo logBo) {
		MultipleDataSource.setDataSourceKey("ris_edi_dev");
		try {
			PlApiRequestLog log = new PlApiRequestLog();
			PlApiRequestContentLog logContent = new PlApiRequestContentLog();
			
			mappingLog(logBo,log);
			
			mappinglogContent(logBo,logContent);
			
			saveLog(log,logContent);
		} catch (Exception e) {
			log.error("记录日志异常",e);
		}finally {
			MultipleDataSource.ClearDataSourceKey();
//			MultipleDataSource.setDataSourceKey(oriDatasource);
		}
	}
	
	public void mappingLog(WmsLogBo logBo,PlApiRequestLog log) {
		log.setRequestCompanyName("RTX");
		log.setRequestApplicationName("WMS");
		log.setRequestEnvironmentName("prod");
		log.setRequestData1(logBo.getStartTime());
		log.setRequestData2(logBo.getEndTime());
		log.setRequestData3(logBo.getMsg());
		
		log.setRequestUrl("http://qimen.api.taobao.com/router/qimen/service");
		
	};
	
	protected void mappinglogContent(WmsLogBo logBo,PlApiRequestContentLog logContent) {
		XmlWriter writer = new XmlWriter(true, "request", QimenRequest.class);
        String requestStr = writer.write(logBo.getApiRequest());
        
        logContent.setRequestContent(requestStr);
        XmlWriter resWriter = new XmlWriter(true, "response", QimenRequest.class);
        String responseStr = resWriter.write(logBo.getApiResponse());
        logContent.setResponseContent(responseStr);
	};
	
	protected void saveLog(PlApiRequestLog log,PlApiRequestContentLog contentLog) {
		String btachid = UUID.randomUUID().toString().replaceAll("-", "");
		log.setLogNo(btachid);
		contentLog.setLogNo(btachid);
		wmsLogMapper.insert(log);
		wmsLogContentLogMapper.insert(contentLog);
	}
}
